package com.ruoyi.project.pay.ali.app;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.ruoyi.project.pay.ali.modal.AliAppPayModal;
import com.ruoyi.project.pay.common.PayUrl;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Filename: AliAppPay.java <br>
 * <p>
 * Description: 支付宝app支付<br>
 *
 * @author: rongrong <br>
 * @version: 1.0 <br>
 * @Createtime: 2019-12-07 <br>
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ---------------------------------------------------------*
 * 2019-12-07       rongrong            v1.0              第一次创建
 * @Copyright: Copyright (c)2019 by rongrong <br>
 */
@Slf4j
public class AliAppPay {

    /**
     * @MethodName: app_pay
     * @Description:  支付宝app支付
     * @param payModal 支付参数
     * @return String 支付所需参数
     * @author lenovo
     * @date 2019-12-07
     */
    public String app_pay(AliAppPayModal payModal){
        //实例化客户端,参数待修改
        AlipayClient alipayClient = new DefaultAlipayClient(PayUrl.SERVER_URL, payModal.getAppid(),
                payModal.getApp_private_key(), PayUrl.FORMAT, PayUrl.CHARSET, payModal.getApp_publice_key(), PayUrl.SIGN_TYPE);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(payModal.getBody());   //内容
        model.setSubject(payModal.getSubject()); //标题
        model.setOutTradeNo(payModal.getOutTradeNo());  //订单号
        model.setTimeoutExpress("30m"); //
        model.setTotalAmount(payModal.getTotal_amount());
        request.setBizModel(model);
        request.setNotifyUrl(payModal.getNotify_url());
        //这里和普通的接口调用不同，使用的是sdkExecute
        AlipayTradeAppPayResponse response = null;
        try {
            response = alipayClient.sdkExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        log.debug(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
        return response.getBody();
    }

    /**
     * 回调验证
     * @param request
     * @return
     */
    public boolean alipayNotify(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        System.out.println("支付宝回调");
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Object o : requestParams.keySet()) {
            String name = (String) o;
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean flag = false;//验签不通过支付宝会一直回调你的异步回调
        AliAppPayModal modal = new AliAppPayModal();
        try {
            flag = AlipaySignature.rsaCheckV1(params,
                    modal.getApp_publice_key(), //这里是支付宝公钥不是应用公钥
                    PayUrl.CHARSET, PayUrl.SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return flag;
    }

}
